import config from '@/config/index.js'
import isPE from '@/utils/isPE.js'


function toOptionStr(obj) {
    let arr = []
    for (let k in obj) {
        arr.push(k + "=" + obj[k])
    }
    return arr.join(",")
}

function open(url) {
    if (true) {
        window.open(url)
        return
    }


    let width = 800
    let height = 500
    let left = (window.innerWidth - width) / 2
    let top = (window.innerHeight - height) / 2
    let options = {
        width,
        height,
        left,
        top,
        location: "no",
        menubar: "no",
        resizable: "no",
        scrollbars: "no",
        status: "no",
        titlebar: "no",
        toolbar: "no",
    }
    window.open(url, '_blank', toOptionStr(options))
}
export default {
    openLoginPage({ commit }, peRedirectPath,funCb) {
        let callback = 'loginCb' + new Date().getTime()
        let cb = (e) => {
            window.removeEventListener('message', cb)
            let data = e.data
            console.log("获取登录响应成功", data)
            commit('setUser', data[callback])
            if(typeof funCb ==='function'){
                funCb(data[callback])
            }
        }
        window.addEventListener('message', cb, false)
        if (isPE()) {
            //pe登录后返回原来的页面
            //pe登录，获取不到window.opener，就调用这个地址，把token传过去
            let peHandleQQLoginPage = window.origin + "/login/handlerQQLogin"
            let params = {
                peRedirectPath,
                peHandleQQLoginPage,
                callback
            }
            let paramsStr = []
            for (const k in params) {
                paramsStr.push(k + "=" + encodeURI(params[k]))
            }
            open(config.loginPage + "?" + paramsStr.join("&"))

        } else {
            open(config.loginPage + "?callback=" + callback)
        }
    }
}
